package com.tree.backend.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tree.backend.common.Result;
import com.tree.backend.entity.dto.costItem.CostItemCreateDTO;
import com.tree.backend.entity.dto.costItem.CostItemQueryDTO;
import com.tree.backend.entity.dto.costItem.CostItemUpdateDTO;
import com.tree.backend.entity.vo.costItem.CostItemTreeNodeVO;
import com.tree.backend.entity.vo.costItem.CostItemVO;
import com.tree.backend.entity.vo.PageVO;
import com.tree.backend.service.ICostItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 成本项目分类表 前端控制器
 * </p>
 */
@RestController
@RequestMapping({"/costItem", "/cost-items"})
public class CostItemController {

    @Autowired
    private ICostItemService costItemService;

    /**
     * 获取成本项目列表（分页）
     */
    @GetMapping("/list")
    public Result<PageVO<CostItemVO>> getCostItemList(CostItemQueryDTO queryDTO) {
        try {
            // 设置默认值
            if (queryDTO.getPage() == null || queryDTO.getPage() < 1) {
                queryDTO.setPage(1);
            }
            if (queryDTO.getPageSize() == null || queryDTO.getPageSize() < 1 || queryDTO.getPageSize() > 100) {
                queryDTO.setPageSize(10);
            }
            
            IPage<CostItemVO> page = costItemService.getCostItemPage(queryDTO);
            
            // 转换为PageVO
            PageVO<CostItemVO> pageVO = new PageVO<>();
            pageVO.setTotal(page.getTotal());
            pageVO.setRecords(page.getRecords());
            pageVO.setSize(page.getSize());
            pageVO.setCurrent(page.getCurrent());
            pageVO.setPages(page.getPages());
            
            return Result.success(pageVO);
        } catch (Exception e) {
            return Result.error(500, "获取成本项目列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取成本项目详情
     */
    @GetMapping("/{id}")
    public Result<CostItemVO> getCostItemDetail(@PathVariable("id") Long id) {
        try {
            CostItemVO costItemVO = costItemService.getCostItemById(id);
            return Result.success(costItemVO);
        } catch (RuntimeException e) {
            return Result.error(400, e.getMessage());
        } catch (Exception e) {
            return Result.error(500, "获取成本项目详情失败：" + e.getMessage());
        }
    }

    /**
     * 新增成本项目
     */
    @PostMapping
    public Result<Boolean> addCostItem(@RequestBody CostItemCreateDTO createDTO) {
        try {
            boolean result = costItemService.addCostItem(createDTO);
            if (result) {
                return Result.success(true);
            } else {
                return Result.error(500, "新增成本项目失败");
            }
        } catch (RuntimeException e) {
            return Result.error(400, e.getMessage());
        } catch (Exception e) {
            return Result.error(500, "新增成本项目失败：" + e.getMessage());
        }
    }

    /**
     * 更新成本项目
     */
    @PutMapping("/{id}")
    public Result<Boolean> updateCostItem(@PathVariable("id") Long id, @RequestBody CostItemUpdateDTO updateDTO) {
        try {
            boolean result = costItemService.updateCostItem(id, updateDTO);
            if (result) {
                return Result.success(true);
            } else {
                return Result.error(500, "更新成本项目失败");
            }
        } catch (RuntimeException e) {
            return Result.error(400, e.getMessage());
        } catch (Exception e) {
            return Result.error(500, "更新成本项目失败：" + e.getMessage());
        }
    }

    /**
     * 删除成本项目
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteCostItem(@PathVariable("id") Long id) {
        try {
            boolean result = costItemService.deleteCostItem(id);
            if (result) {
                return Result.success(true);
            } else {
                return Result.error(500, "删除成本项目失败");
            }
        } catch (RuntimeException e) {
            return Result.error(400, e.getMessage());
        } catch (Exception e) {
            return Result.error(500, "删除成本项目失败：" + e.getMessage());
        }
    }

    /**
     * 获取成本项目树
     */
    @GetMapping("/tree")
    public Result<List<CostItemTreeNodeVO>> getCostItemTree() {
        try {
            List<CostItemTreeNodeVO> tree = costItemService.getCostItemTree();
            return Result.success(tree);
        } catch (Exception e) {
            return Result.error(500, "获取成本项目树失败：" + e.getMessage());
        }
    }

    /**
     * 获取所有成本项目列表（不分页）
     */
    @GetMapping("")
    public Result<List<CostItemVO>> getAllCostItems() {
        try {
            List<CostItemVO> costItems = costItemService.getAllCostItems();
            return Result.success(costItems);
        } catch (Exception e) {
            return Result.error(500, "获取所有成本项目失败：" + e.getMessage());
        }
    }
}
